;
(function (call) {
    var pqpf = {
        mapId: "tjMap",
        selectedPro: [],
        playList: null,
        router: {
            cfg: "/business/szyb/json/pqpf.json",
            gridBysData: 'sjyb/queryGlYBRainGridData',
            getBysLatestTime: 'sjyb/queryGridDataLatestTime',
            gridRankData: 'zhfx/gridKGYB/queryRankPyGridData',
            gridRankDesc: 'zhfx/gridKGYB/queryRankPyGridDataDesc',
            getRankLatestTime: 'zhfx/gridKGYB/queryRankPyGridDataLatestTime',
        },
        init: function () {
            var that = this;
            $.getJSON(that.router.cfg, function (cfg) {
                if (cfg) {
                    that.buildContainer(cfg);
                    that.bindEvt();
                }
            })
        },
        // 获取最新起报时间
        getLatestTime: function (call) {
            var that = this;
            var pro = $(".product-pqpf-list li").first().data('pro');
            var url = this.router.getBysLatestTime;
            if (pro.group == 'rank')
                url = this.router.getRankLatestTime;
            var param = {
                element: pro.ele_id
            };
            $.ajax({
                url: url,
                type: 'GET',
                dataType: 'json',
                async: false,
                data: param
            }).done(function (res) {
                if (res.isSuccess && res.data) {
                    $(".product-pqpf-datepicker #pqpfDate").IDatePicker().setVal(res.data);
                    that.buildLastTime();
                }
            })
        },
        showRankDesc: function () {
            var that = this;
            var proType = $('.product-pqpf-tab li.active').data('model').id;
            if (proType != 'rank') return;

            var eleId = $(".product-pqpf-list li.active").data('pro').ele_id;
            var param = {
                queryTime: this.getQbTime(),
                element: eleId
            }
            $('.cafe-busis-rankdesc').remove();
            $.get(that.router.gridRankDesc,param, function (data) {
                if (!data) return;
                $(".cafe-busis-container").append(`
                    <div class="cafe-busis-rankdesc">${data}</div>
                `)
            })
        },
        /**
         * 构建弹出框内容
         */
        buildContainer: function (data) {
            var that = this;
            if (!data) {
                return;
            }
            data.pro_type.forEach(function (item) {
                var $li = $(`<li>${item.name}</li>`);
                $li.data('model', item);
                $li.off().click(function () {
                    if ($(this).hasClass("active")) {
                        return;
                    }
                    that.delAllLayer(); //切换模式后, 清空之前模式数据
                    $(this).addClass("active").siblings().removeClass("active");
                    $('.product-pqpf-datepicker').empty()
                        .append(`
                          <div class="date-panel">
                            <input class="DateAgent" id="pqpfDate" data-options="${item.dateOptions}" value="">
                            <i class="btn-forward"></i>
                            <i class="btn-backward"></i>
                            <i class="btn-newest"></i>
                          </div>`);
                    $.IDate(".product-pqpf-datepicker .date-panel", {
                        query: function query() {
                            pqpf.buildLastTime(function () {
                                pqpf.getMultiGridData();
                            });
                        }
                    });

                    that.buildProContent(data.basic_pro[item.id] || [], item.id);

                    that.getLatestTime();
                    that.buildLastTime();
                    $('.cafe-busis-rankdesc').remove();
                    $(".product-pqpf-list").find('li.default').trigger('click');
                })
                $(".product-pqpf-tab ul").append($li);
            })
            $(".product-pqpf-tab").show();
        },
        /**
         * 构建要素展示
         * data 要素列表
         */
        buildProContent: function (data,proId) {
            var that = this;
            debugger
            $(".product-pqpf-list").empty();
            data.forEach(function (item) {
                var $item = $('<div>').addClass('product-item');

                var $title = $('<div>').addClass('product-title');
                $title.data('type', item.group_id);
                $title.html(item.group_name);
                $item.append($title);
                if (item.content) {
                    var $ul = $('<ul>');
                    item.content.forEach(function (pro) {
                        var $li = $(`<li><span>${pro.ele_name}</span></li>`);
                        if (pro.selected)
                            $li.addClass("default");
                        pro.group = item.group_id;
                        $li.data('pro', pro);
                        if (pro.title)
                            $li.attr('title', pro.title);
                        if (pro.width)
                            $li.css("width", pro.width);
                        $ul.append($li);
                    })
                    $item.append($ul);
                }
                
                $(".product-pqpf-list").append($item);
            })
        },
        //点击显示pdf技术说明
        showTechPdf:function(id,path){
            var that = this;
            if (CafeJS.ModalBoxExist(id)) {
                CafeJS.ModalBoxShow(id);
                return;
            }
            CafeJS.ModalBox({
                id: id,
                container: 'cafe-busis-container',
                title: "技术说明",
                width: 1300,
                height: 700,
                m_top: 70,
                m_right: 90,
                hasMask:true,
                hide: true,
                html: "<div id='"+id+"' style='width:100%;height:calc(100% - 10px)'></div>",
                showCall: function(obj) {
                    PDFObject.embed(path,"#"+id);
                },
                closed: function () { }
            });
        },
        // 初始化最近起报时间
        buildLastTime: function (call) {
            var interval = $(".product-pqpf-tab li.active").data("model").interval;
            var baseDate = this.getQbTime();
            var newDate = new Date(baseDate);
            var liArr = [];
            for (var i = 0; i < 4; i++) {
                liArr.push(`<li class="${i == 0 ? 'active' : ''}" data-time="${newDate}">${newDate.format("ddhh")}</li>`);
                newDate.setHours(newDate.getHours() - interval);
            }
            $(".product-pqpf-datechange ul").empty().append(liArr.reverse().join(""));

            if (this.playList) {
                this.playList.init({
                    curDate: baseDate
                });
                if ($.isFunction(call))
                    call();
            }
        },
        // 初始化播放列表
        initPlayList: function (pro) {
            var that = this;
            var startTime = pro.time;

            var layers = that.getModels(pro.ele);
            var maxHour = Number($('.product-pqpf-tab li.active').data('model').maxHour);
            var interval = ($('.product-pqpf-list li.active').data('pro').interval || 24) * 60;
            this.playList = CafeJS.Timeline2({
                appendTo: "#a-m-timeline",
                curDate: startTime,
                type: 1,
                pro: pro,
                maxHour: maxHour,
                dateOpt: {
                    dateFmt: 'yyyy-MM-dd hh',
                    timeInterval: 12,
                    customHm: [8, 20]
                },
                timeInterval: interval,
                layers: layers,
                gisId: that.mapId,
                call: function (pro) {
                    pro.forecastTime = that.playList.getCurTime();
                    CafeJS.layerManage.updateLayer(pro);

                    that.getModelGridData(pro);
                },
                getPlayData: function (pro, timeArr) {
                    that.getModelGridData(pro, timeArr);
                }
            });
            pro.forecastTime = that.playList.getCurTime();
            if (CafeJS.layerManage)
                CafeJS.layerManage.updateLayer(pro);
        },
        // 初始化图例
        initLegentpicker: function (ele, appendTo) {
            var that = this;
            var layers = that.getModels(ele);
            var layerIds = [];
            $.each(layers, function (i, m) {
                layerIds.push(m.id);
            });
            CafeJS.legentPicker = CafeJS.Legentpicker({
                appendTo: appendTo,
                gisId: that.mapId,
                layerId: layerIds,
                totalWidth: 400,
                h_legend: 15,
                seq: 'decrease',
                productId: ele.color_id,
                isShowSlider: true
            });
        },
        getQbTime: function() {
            var qbTime = $(".product-pqpf-datepicker #pqpfDate").IDatePicker().getVal() + ":00:00";
            return qbTime;
        },
        // 获取选中的要素格点数据
        getMultiGridData: function () {
            var that = this;
            if (this.selectedPro.length === 0) return;
            this.selectedPro.forEach(function (pro) {
                var proInfo = that.getProInfo(pro);
                that.getModelGridData(proInfo);
            })
            var forecastTime = that.playList.getCurTime();
            var qbTime = this.getQbTime();
            CafeJS.layerManage.updateLayerTime(qbTime, 'pqpf', forecastTime);

            this.showRankDesc();
        },
        getModelGridData: function (proInfo, timeArr) {
            var that = this;
            if (!proInfo) return;
            var pro = proInfo.ele,
                params = {};
            var element = pro.ele_id;
            var queryTime = that.playList.getCurTime() + ":00";
            var qbTime = new Date(proInfo.time).format('yyyy-MM-dd hh:mm:ss');
            var arr = [], period;
            if (pro.group == 'rank') {
                if (timeArr) {
                    timeArr.split(',').forEach(function (i) {
                        aging = (new Date(i).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
                        arr.push(aging);
                    })
                } else {
                    period = (new Date(queryTime).getTime() - new Date(qbTime).getTime()) / 1000 / 60 / 60;
                    arr.push(period);
                }
                params = {
                    queryTime: qbTime,
                    element: element,
                    period: arr.join(",")
                }
                url = that.router.gridRankData;
            } else {
                var modelTab = $('.product-pqpf-tab li.active').data('model');
                if (timeArr) {
                    arr = timeArr.split(",");
                } else {
                    arr.push(queryTime);
                }
    
                params = {
                    qbTime: qbTime,
                    element: element,
                    ybTimes: arr.join(","),
                    area: modelTab.area,
                    height: modelTab.height,
                    maxHour: modelTab.maxHour,
                    model: modelTab.model || 'JSGL'
                }
                url = that.router.gridBysData;
            }
            
            CafeJS.ajax({
                url: url,
                params: params,
                type: "GET",
                success: function (e) {
                    var arrayBuffer = e.response;
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        that.clearGridLayer(element);
                        return;
                    }
                    that.drawGridRawMap(arrayBuffer, pro);
                }
            })
        },
        // 绘制格点色斑图
        drawGridRawMap: function (data, pro) {
            var typeArr = this.getModels(pro);

            var color_id = pro.color_id;
            var legentCfg = CafeJS.Legentconfig().cfg();
            var colorObj = legentCfg[color_id];

            // 显示色斑和数值
            GIS.GridShow.showByTypes_raw(this.mapId, typeArr, data, {}, colorObj);
            CafeJS.legentPicker.updateLegentRange(typeArr,this.mapId);
        },
        //获取要素样式
        getModels: function (pro) {
            var models = [];
            $.each(pro.models.split(","), function (i, m) {
                var layerId = "pqpf-layer-" + m + "-" + pro.ele_id;
                models.push({
                    type: m,
                    visible: true,
                    uv: false,
                    wd: true,
                    cacheConfig: 'noCache',
                    id: layerId
                });
            });
            return models;
        },
        // 增加产品图层
        addLayerManage: function (proInfo) {
            var that = this;
            if (CafeJS.layerManage) {
                CafeJS.layerManage.addLayer(proInfo);
            } else {
                CafeJS.layerManage = CafeJS.LayerManage({
                    appendTo: "#c-b-layermanage",
                    mapId: that.mapId,
                    proInfo: proInfo,
                    call: function (pro) {
                        CafeJS[pro.bussitype].initPlayList(pro);
                    },
                    close: function (pro) {
                        CafeJS[pro.bussitype].delLayer(pro);
                    }
                })
            }
            if (proInfo.isGrid && !proInfo.ele.frames) {
                that.initLegentpicker(proInfo.ele, '.cafe-layer-item.active');
            }
        },
        // 删除图层后取消要素选择
        delLayer: function (pro) {
            var eleid = pro.ele.ele_id;
            if (pro.isGrid) {
                $(".product-pqpf-list li.active").each(function () {
                    if ($(this).data('pro').ele_id == eleid) {
                        $(this).click();
                        return false;
                    }
                })

                $(".product-pqpf-list td.active").each(function () {
                    if ($(this).data('pro').ele_id == eleid) {
                        $(this).click();
                        return false;
                    }
                })
            }

        },
        // 删除该模式所有的要素数据
        delAllLayer: function () {
            $(".product-pqpf-list li.active").each(function () {
                $(this).click();
            })
        },
        // 移除当前要素的图层
        removeLayer: function (ele) {
            var proInfo = this.getProInfo(ele);
            CafeJS.layerManage.removeLayer(proInfo);
        },
        getProInfo: function (ele) {
            var height = ele.height != undefined ? ele.height : '';
            var name = $('.product-pqpf-tab li.active').data('model').name;
            name += '_' + height + ele.ele_name;
            var time = this.getQbTime();
            var proInfo = {
                name: name,
                time: time,
                bussitype: 'pqpf',
                ele: ele,
                isGrid: true,
                isSK: false
            }
            return proInfo;
        },
        // 清除格点图层
        clearGridLayer: function (ele_id) {
            var layerIds = [];
            if (!ele_id) return;
            GLMap.layerIds.forEach(function (layerId) {
                if (layerId.indexOf('pqpf-layer') != -1 && layerId.indexOf(ele_id) != -1) {
                    layerIds.push(layerId);
                }
            })
            GIS.LayerControll.deleteLayer(this.mapId, layerIds);
        },
        /**
         * 绑定事件操作
         */
        bindEvt: function () {
            var that = this;
            // 要素点击事件
            $(".product-pqpf-list").off('click').on('click', 'li', function () {
                var pro = $(this).data('pro');
                if(pro.pdf_path){
                    that.showTechPdf(pro.ele_id,pro.pdf_path);
                    return false;
                }
                if ($(this).hasClass("active")) {
                    $(this).removeClass("active");

                    that.selectedPro = that.selectedPro.filter(item => item.ele_id != pro.ele_id);

                    that.clearGridLayer(pro.ele_id);
                    that.removeLayer(pro);
                    $('.cafe-busis-rankdesc').remove();
                } else {
                    $(this).siblings('li.active').click(); // 清除之前选中的

                    $(this).addClass("active");

                    that.selectedPro.push(pro);

                    var proInfo = that.getProInfo(pro);
                    // 增加产品图层
                    that.addLayerManage(proInfo);

                    that.getModelGridData(proInfo);

                    that.showRankDesc();
                }
            })
            // 最近起报时间
            $(".product-pqpf-datechange").delegate('li', 'click', function () {
                $(this).addClass("active").siblings().removeClass("active");
                var time = $(this).data('time');
                $(".product-pqpf-datepicker #pqpfDate").IDatePicker().setVal(time);

                that.playList.init({
                    curDate: time
                });

                that.getMultiGridData();
            })
            $('.product-pqpf-datepicker').off('click').on('click', '.btn-forward', function (e) { // 日期向前
                e.stopPropagation();
                $(".product-pqpf-datepicker #pqpfDate").IDatePicker().toForward();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            }).on('click', '.btn-backward', function (e) { // 日期向后
                e.stopPropagation();
                $(".product-pqpf-datepicker #pqpfDate").IDatePicker().toBackward();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            }).on('click', ".btn-newest", function (e) { // 最新
                e.stopPropagation();
                $(".product-pqpf-datepicker #pqpfDate").IDatePicker().toNewest();
                that.buildLastTime(function () {
                    that.getMultiGridData();
                });
            });
            $(".product-pqpf-tab li").first().click();
        }
    }
    if (typeof call === 'function') {
        CafeJS.pqpf = pqpf;
        call(pqpf);
    }
    window.pqpf = pqpf;
})(function (pqpf) {
    CafeJS.models(['ajax', 'legentconfig', 'legentpicker', 'timeLine2'], function () {
        pqpf.init();
    });
});